package com.quzi.kettle.activitise.added;

import java.io.IOException;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

public class VoiceRecordUtil {
	// private String FileName = null;
	private static final String LOG_TAG = "AudioRecordTest";
	private static MediaPlayer mPlayer = null;
	private static MediaRecorder mRecorder = null;

	private static String getFileName() {
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/audiorecordtest.3gp";
	}

	public static void startRecord() {
		stopRecord();
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		mRecorder.setOutputFile(getFileName());
		try {
			mRecorder.prepare();

		} catch (IOException e) {
			Log.e(LOG_TAG, "prepare() failed");
			stopRecord();
		}
		mRecorder.start();
	}

	public static void stopRecord() {
		if (mRecorder != null) {
			mRecorder.stop();
			mRecorder.reset();
			mRecorder.release();
			mRecorder = null;
		}

	}

	public static void Destory() {
		stopPlay();
		stopRecord();
	}

	public static void startPlay(Context context) {

		// if (mPlayer == null) {
		// mPlayer = MediaPlayer.create(context, Uri.parse(getFileName()));
		//
		// } else {
		// if (mPlayer.isPlaying()) {
		// mPlayer.stop();
		// }
		// }
		//
		// // mPlayer = MediaPlayer.create(context, Uri.parse(getFileName()));
		//
		// try {
		//
		// //mPlayer.setDataSource(getFileName());
		// mPlayer.prepare();
		// mPlayer.start();
		// } catch (IOException e) {
		// Log.e(LOG_TAG, "播放失败");
		// stopPlay();
		// } finally {
		// stopPlay();
		// }
		stopPlay();
		mPlayer = new MediaPlayer();

		try {
			mPlayer.setDataSource(getFileName());
			mPlayer.prepare();
			mPlayer.start();
		} catch (IOException e) {
			Log.e(LOG_TAG, "prepare() failed");
		}

	}

	public static void stopPlay() {
		if (mPlayer != null) {
			if (mPlayer.isPlaying()) {
				mPlayer.stop();
			}
			mPlayer.reset();
			mPlayer.release();
			mPlayer = null;
		}

	}
}
